package pers.wwz.study.wechatserver.common;

import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import pers.wwz.study.wechatserver.exception.BaseExceptionCode;

import java.io.Serializable;

@Data
@NoArgsConstructor
@ToString
public class DataResponse<T> implements Serializable {
    private static final long serialVersionUID = 1L;
    public static final String SUCCESS = "200";
    private static final String SUCCESS_MSG = "操作成功";
    public static final String ERROR = "9999999";
    public static final String INITIATIVE_ERROR = "-1";
    private static final String ERROR_MSG = "操作失败";
    /**
     * "返回码"
     */
    private String code;
    /**
     * "返回消息"
     */
    private String message;
    /**
     * "返回业务对象"
     */
    private T data;


    public DataResponse(T data) {
        this.data = data;
    }

    public DataResponse(String code, String message) {
        this.code = code;
        this.message = message;
    }

    public DataResponse(String code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public static <T> DataResponse<T> succeed() {
        return new DataResponse<T>(DataResponse.SUCCESS, DataResponse.SUCCESS_MSG);
    }

    public static <T> DataResponse<T> succeed(T data) {
        return new DataResponse<T>(DataResponse.SUCCESS, DataResponse.SUCCESS_MSG, data);
    }

    public static <T> DataResponse<T> succeed(String message, T data) {
        return new DataResponse<T>(DataResponse.SUCCESS, message, data);
    }

    public static <T> DataResponse<T> faild() {
        return new DataResponse<T>(DataResponse.ERROR, DataResponse.ERROR_MSG);
    }

    /**
     * 不建议使用，此方法返回 code= 9999999 前端无法判断是调用服务失败还是业务失败
     * 代替方案为抛出异常 throw new ServiceException(CommonExceptionCode.COMMON_EXCEPTION_CODE,"message");
     */
    @Deprecated
    public static <T> DataResponse<T> faild(String message) {
        return new DataResponse<T>(DataResponse.ERROR, message);
    }


    /**
     * 调用服务成功,但是业务失败
     * @param message
     * @param <T>
     * @return
     */
    public static <T> DataResponse<T> initiativeFail(String message) {
        return new DataResponse<T>(DataResponse.INITIATIVE_ERROR, message);
    }

    public static <T> DataResponse<T> faild(T data) {
        return new DataResponse<T>(DataResponse.ERROR, DataResponse.ERROR_MSG, data);
    }
    public static <T> DataResponse<T> faild(BaseExceptionCode exceptionCode) {
        return new DataResponse<T>(exceptionCode.getValue(), exceptionCode.getMessage());
    }

    public static <T> DataResponse<T> faild(BaseExceptionCode exceptionCode, T data) {
        return new DataResponse<T>(exceptionCode.getValue(), exceptionCode.getMessage(), data);
    }


    public boolean isSuccess() {
        return !ERROR.equals(code);
    }
}
